<?php

namespace app\admin\controller\my;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

/**
 * 项目文件管理
 *
 * @icon fa fa-user
 */
class ArticleFile extends Backend
{

    protected $relationSearch = true;
    protected $noNeedRight = ["download", "look"];

    protected $isAuth = 0;

    /**
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\department\ArticleFile;
        $article_id = $this->request->param("article_id");
        $this->assign("article_id", $article_id);
        if ($this->request->action() != "add" && $this->request->action() != "del") {
            $model = new \app\admin\model\department\Article;
            $articleRow = $model->get($article_id);
            if (empty($articleRow)) {
                $this->error("数据错误");
            }

            $selfIsAuth = 0;
            if ($articleRow->create_uid == $this->auth->id) {
                //是否创建者
                $selfIsAuth = 1;
            } else {
                $model = new \app\admin\model\department\ArticleUser;
                //是否该项目管理员
                $wheres = [
                    "article_id" => $articleRow->id,
                    "user_id" => $this->auth->id,
//                    "is_auth" => 1
                ];
                $exits = $model->where($wheres)->find();
                if (!empty($exits)) {
                    $selfIsAuth = 1;
                }
            }
            $this->isAuth = $selfIsAuth;
            $this->assign("selfIsAuth", $selfIsAuth);
            $this->assignConfig("selfIsAuth", $selfIsAuth);
        }

    }


    public function index($article_id = null)
    {
        $row = \app\admin\model\department\Article::where(['id' => $article_id])->find();
        if (empty($row)) {
            $this->error("数据错误");
        }
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wheres = [
                "article_id" => $row->id
            ];
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where($wheres)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $filename = explode(".", $v->file);
                if (in_array(end($filename), ["doc", "docx", "xls", "xlsx", "csv", "ppt", "pptx"])) {
                    $path = "/office2pdf/" . $v->file_name . ".pdf";
                } else {
                    $path = $v->file;
                }
                $v->file_path = $path;
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignConfig("article_id", $row->id);
        $this->assignConfig("isAuth", $this->_checkDownloadAuth($row->id));
        return $this->view->fetch();
    }

    public function add($article_id = null)
    {
        $row = \app\admin\model\department\Article::where(['id' => $article_id])->find();
        if (empty($row)) {
            $this->error("数据错误");
        }
        if ($row->publish == 1) {
            $this->error("已发布禁止上传", '', '', '');
        }
		
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
		
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
			$files = explode(",", $params["file"]);
			foreach ($files as $value) {
				$params["file"] = $value;
                $tempArr = explode("/", $params['file']);
                if (!empty($tempArr[3])) {
                    $tempArr = explode(".", $tempArr[3]);
                    $params['file_name'] = $tempArr[0];
                    $path = APP_PATH . "../public/office2pdf/" . $params['file_name'] . ".pdf";
                    $params['file_content'] = parsePdf($path) ?? null;
                }
				$result = $this->model->allowField(true)->isUpdate(false)->insert($params);
				if ($result === false) {
					exception("上传失败");
				}
			}

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null, $article_id = null)
    {
        $row = \app\admin\model\department\Article::where(['id' => $article_id])->find();
        if (empty($row)) {
            $this->error("数据错误");
        }
        if ($row->publish == 1) {
            $this->error("已发布禁止修改", '', '', '');
        }
        $model = new \app\admin\model\department\ArticleUser;
        //是否该项目管理员
        $wheres = [
            "article_id" => $row->id,
            "user_id" => $this->auth->id,
            "is_auth" => 1
        ];
        $exits = $model->where($wheres)->find();
        $fileRow = $this->model->get($ids);
        //不是管理员，又不是自己上传的文件，禁止删除
        if (empty($exits) && $fileRow->user_id != $this->auth->id) {
            $this->error("暂无权限编辑", '', '', '');
        }
        return parent::edit($ids);
    }

    public function del($ids = null, $article_id = null)
    {
        $row = \app\admin\model\department\Article::where(['id' => $article_id])->find();
        if (empty($row)) {
            $this->error("数据错误");
        }
        if ($row->publish == 1) {
            $this->error("已发布禁止操作", '', '', '');
        }

        $model = new \app\admin\model\department\ArticleUser;
        //是否该项目管理员
        $wheres = [
            "article_id" => $row->id,
            "user_id" => $this->auth->id,
            "is_auth" => 1
        ];
        $exits = $model->where($wheres)->find();
        $fileRow = $this->model->get($ids);
        //不是管理员，又不是自己上传的文件，禁止删除
        if (empty($exits) && $fileRow->user_id != $this->auth->id) {
            $this->error("暂无权限删除", '', '', '');
        }
        parent::del($ids);
    }

    public function look()
    {
        $article_id = $this->request->param('article_id', 0);
        $file_id = $this->request->param('file_id', 0);
        $row = \app\admin\model\department\Article::where(['id' => $article_id])->find();
        if (!empty($row)) {
            $logContent = "查看课题【{$row['title']}】文件";
            $fileRow = $this->model->get($file_id);
            if (!empty($fileRow)) {
                $logContent .= "：{$fileRow['name']}";
            }
            $map = [
                "title" => "查看课题文件",
                "content" => $logContent,
                "admin_id" => $this->auth->id,
                "username" => $this->auth->nickname,
                "url" => "/admin/my/article_file/look",
                "ip" => request()->ip(),
                'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            ];
            (new \app\admin\model\AdminLog)->save($map);
        }
    }

    //下载附件
    public function download()
    {
        ini_set('memory_limit', '2048M'); //内存限制放宽
        set_time_limit(0); //运行时间不限制
        $article_id = $this->request->param('article_id', 0);
        $list = \app\admin\model\department\Article::whereIn('id', $article_id)->select();
        if (empty($list)) {
            $this->error("数据错误");
        }
		$noAuthIds = [];
        //检测下载权限
        foreach ($list as $row) {
            if ($row->is_public) {
                continue;
            }
            $downAuth = $this->_checkDownloadAuth($row->id);
            $title = "";
//            !$downAuth && $this->error(mb_substr($row->title, 0, 10) . "：暂无下载权限", '', '', '');
            if (!$downAuth) {
                $noAuthIds[] = $row->id;
            }
        }

        $random = new \fast\Random;
        $files = array(); //要打包的所有文件
        $names = [];
        $logContent = "";
        $allFiles = [];
        foreach ($list as $row) {
			$row->down_num += 1;
			$row->save();
            if (empty($logContent)) {
                $logContent = "课题名称：" . $row['title'];
            } else {
                $logContent = '、' . $row['title'];
            }

            $where = [
                "article_id" => $row->id
            ];
            $listTemp = $this->model->where($where)->select();
            foreach ($listTemp as $value) {
                $allFiles[] = array(
                    "title" => $row['title'],
                    "name" => $value['name'],
                    "name2" => $value['name2'],
                );
                if (!empty($value->file)) {
                    $key = $random::alnum();
                    $files[$key] = $value->file;
                    $names[$key] = $value->article_id . ":" . $value->name;
                }
            }
        }


        if (empty($files)) {
            echo "没有文件可以下载";die;
        }

        \app\admin\model\AdminLog::record('文件下载', $logContent);

        if (!empty($noAuthIds)) {
            $this->export($allFiles);
        }

        $name = date("Y-m-d") . "下载";
        $zipName = ROOT_PATH . "public/download/{$name}.zip";
        $zip = new \ZipArchive;
        if (!file_exists($zipName)) {
            $res = $zip->open($zipName, \ZipArchive::CREATE);
        } else {
            $res = $zip->open($zipName, \ZipArchive::OVERWRITE);
        }
        if ($res !== TRUE) {
            echo "无法打开文件，或者文件创建失败";die;
        }
        foreach($files as $key => $val){
            //$attachfile = $attachmentDir . $val['filepath']; //获取原始文件路径
            $val = ROOT_PATH . "public" . $val;
            $type = explode(".", $val);
            if(file_exists($val)){
                //addFile函数首个参数如果带有路径，则压缩的文件里包含的是带有路径的文件压缩
                //若不希望带有路径，则需要该函数的第二个参数
                $name = $random::alnum(32) . "." . $type[1];
                if (isset($names[$key])) {
                    $name = $names[$key] . "-" . $random::alnum() . "." . $type[1];
                }
                $zip->addFile($val, $name);//第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
            }
        }
        $zip->close();//关闭

        if(!file_exists($zipName)){
            exit("无法找到文件"); //即使创建，仍有可能失败
        }
        
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.basename($zipName)); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: '. filesize($zipName)); //告诉浏览器，文件大小
        @readfile($zipName);
    }
    private function _checkDownloadAuth($articleId): bool
    {
        $model = new \app\admin\model\department\ArticleUser;
        $bandUserWhere = [
            "article_id" => $articleId,
            "user_id" => $this->auth->id
        ];
        $exits = $model->where($bandUserWhere)->find();
        if (!empty($exits)) {
            return true;
        }

        $model = new \app\admin\model\department\ArticlePublish;
        $adminModel = new \app\admin\model\Admin;
        $row = $adminModel->get($this->auth->id);
        //检测部门
        if (!empty($row['department_id'])) {
            $where = array(
                "type" => 1,
                "article_id" => $articleId,
                "with_id" => $row['department_id']
            );
            $exits = $model->where($where)->value("id");
            if (!empty($exits)) return true;
        }
        //检测职务
        if (!empty($row['position_id'])) {
            $where = array(
                "type" => 2,
                "article_id" => $articleId,
                "with_id" => $row['position_id']
            );
            $exits = $model->where($where)->value("id");
            if (!empty($exits)) return true;
        }
        //检测类别
        if (!empty($row['type_id'])) {
            $where = array(
                "type" => 3,
                "article_id" => $articleId,
                "with_id" => $row['type_id']
            );
            $exits = $model->where($where)->value("id");
            if (!empty($exits)) return true;
        }


        return false;
    }


    private function export($result)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $styleArray = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
            ],
//            'borders' => [
//                'outline' => [
//                    'borderStyle' => Border::BORDER_THICK,
//                ],
//            ],
        ];
        $sheet->getDefaultColumnDimension()->setWidth(60);// 列宽
        $sheet->getDefaultRowDimension()->setRowHeight(20);// 行高

        $tabletitle = '项目文件信息';
        $sheet->mergeCells('A1:C1');
        $sheet->getRowDimension('1')->setRowHeight(30);// 行高
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(16);
        $sheet->setCellValue('A1', $tabletitle);
        $sheet->getStyle('A2:C2')->applyFromArray($styleArray);

        $sheet->getStyle('A2:C2')->getFont()->setBold(true)->setSize(12);
        $sheet->setCellValue('A2','项目名称');
        $sheet->setCellValue('B2','文件名');
        $sheet->setCellValue('C2','文件摘要');

        //输出表格
        foreach ($result as $key => &$val) {
            $i = $key + 3;//表格是从3开始的
            $sheet->setCellValue('A' . $i, $val['title']);
            $sheet->setCellValue('B' . $i, $val['name']);
            $sheet->setCellValue('C' . $i, $val['name2']);
        }

        // 工作簿标题
        $sheettitle = '项目文件信息';
        $sheet->setTitle($sheettitle);

        $outputFileName = "项目文件信息.". time() .".xls";

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $outputFileName . '"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $write = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $write->save('php://output');
        exit;
    }

}
